package model

import (
	"gorm.io/gorm"
	"time"
)

// Consultation 问诊模型
type Consultation struct {
	gorm.Model
	OrderNo             string    `gorm:"type:varchar(32);not null;unique;comment:订单号"`
	PatientID           int64     `gorm:"type:bigint;not null;index;comment:患者ID"`
	DoctorID            int64     `gorm:"type:bigint;not null;index;comment:医生ID"`
	ConsultationType    int       `gorm:"type:tinyint(1);not null;comment:问诊类型:1-图文,2-语音,3-视频"`
	SymptomDescription  string    `gorm:"type:text;comment:症状描述"`
	AttachmentUrls      string    `gorm:"type:text;comment:附件URLs,用逗号分隔"`
	Status              int       `gorm:"type:tinyint(1);not null;default:0;comment:状态:0-待接诊,1-进行中,2-已完成,3-已取消"`
	StartTime           time.Time `gorm:"comment:开始时间"`
	EndTime             time.Time `gorm:"comment:结束时间"`
	Amount              float64   `gorm:"type:decimal(10,2);comment:金额"`
}

// ConsultationRating 问诊评价
type ConsultationRating struct {
	gorm.Model
	ConsultationID int64  `gorm:"type:bigint;not null;unique;comment:问诊ID"`
	Rating         int    `gorm:"type:tinyint(1);not null;comment:评分:1-5星"`
	Comment        string `gorm:"type:text;comment:评价内容"`
}

// CreateConsultation 创建问诊
func (c *Consultation) CreateConsultation(db *gorm.DB) error {
	return db.Create(&c).Error
}

// GetConsultationByID 根据ID查询问诊
func (c *Consultation) GetConsultationByID(db *gorm.DB, id int64) error {
	return db.Where("id = ?", id).First(&c).Error
}

// UpdateConsultation 更新问诊
func (c *Consultation) UpdateConsultation(db *gorm.DB) error {
	return db.Save(&c).Error
}

// GetConsultationList 获取问诊列表
func GetConsultationList(db *gorm.DB, userId int64, userType, page, pageSize int) ([]Consultation, int64, error) {
	var consultations []Consultation
	var total int64

	query := db.Model(&Consultation{})
	if userType == 1 {
		// 医生
		query = query.Where("doctor_id = ?", userId)
	} else {
		// 患者
		query = query.Where("patient_id = ?", userId)
	}

	// 统计总数
	if err := query.Count(&total).Error; err != nil {
		return nil, 0, err
	}

	// 使用分页作用域
	if err := query.Scopes(Paginate(page, pageSize)).Order("created_at DESC").Find(&consultations).Error; err != nil {
		return nil, 0, err
	}

	return consultations, total, nil
}

// CreateConsultationRating 创建问诊评价
func (r *ConsultationRating) CreateConsultationRating(db *gorm.DB) error {
	return db.Create(&r).Error
}

